'use strict';

var reviewResult = null,
    reviewCurrentEl,
    // 记录当前点击元素
reviewCurrentLevel,
    // 记录当前点击级别
reviewCurrentType; // 记录当前点击类型

$(function () {

    // 加载layui需要的组件
    layui.use(['layer', 'element'], function () {
        var layer = layui.layer,
            element = layui.element();

        // 打开用户选择弹层
        $(document).on('click', '.review-user-avatar', function (ev) {
            var level = $(this).attr('review-level'),
                type = $(this).attr('review-type'),
                isOptional = typeof $(this).parent().attr('optional') == 'undefined' ? false : true,
                isAdd = typeof $(this).parent().attr('add') == 'undefined' ? false : true,
                data;

            // optional和add必定存在一种情况，deletable则不需要打开弹层
            if (!isOptional && !isAdd) return;

            // 将点击时的元素及类型记录下来
            reviewCurrentEl = $(this);
            reviewCurrentType = type;
            reviewCurrentLevel = level;

            // 存在规则和不存在规则传入的数据有所区别并赋值给data，data最后作用于渲染源数据
            if (reviewResult.isRuleActive) {
                data = type == 'reviewers' ? [reviewResult.reviewers[level]] : reviewResult.cc;
            } else {
                data = reviewResult.users;
            }

            // 并不是任何情况都需要检查
            if (type == 'reviewers' && isOptional && data.length == 1) {
                if (data[0].users.length == 1) {
                    layer.msg('当前审批等级候选人只有一位，无需手动选择。', {
                        icon: 0,
                        time: 2000,
                        area: ['375px']
                    });
                    return false;
                }
            }

            var content = renderUserSelector(data, type, level);

            layer.open({
                type: 1,
                id: 'layerUserSelector',
                title: '请选择用户',
                area: ['100%', '100%'],
                content: content,
                scrollbar: false,
                success: function success(layero, index) {
                    // 为防止layer.open打开之后事件或样式出错，当弹层打开后初始化element
                    element.init();
                }
            });
        });

        // 弹层内选择用户
        $(document).on('click', '#layerUserSelector .review-user-avatar', function () {
            // 拼装需要加载至页面的dom结构
            var dom = '',
                cate = 'deletable',
                userbox = $(this).parent(),
                insertMode = 'insert';

            if (reviewResult.isRuleActive) {
                if (reviewCurrentType == 'reviewers') {
                    cate = 'optional';
                    insertMode = 'replace';
                }
            }

            // 收集点击的用户数据
            var userId = userbox.find('input[type=hidden]').val(),
                face = userbox.find('.review-user-avatar img').attr('src'),
                nickname = userbox.find('.review-user-name').text(),
                postname = userbox.find('.review-user-footer').text();

            // 检测用户是否已经存在，避免出现重复的用户
            var reviewBlock = reviewCurrentEl.parent().parent(),
                isRepeat = false; // 是否存在重复记录的标识

            // 遍历对比已选择的用户
            reviewBlock.children().each(function (index) {
                if ($(this).find('input[type="hidden"][name="' + reviewCurrentType + '[' + userId + ']"][value="' + userId + '"]').length > 0) {
                    layer.msg(nickname + '已存在', {
                        icon: 0
                    });
                    isRepeat = true;
                    return false;
                }
            });
            if (isRepeat) return;

            var user = {
                id: userId,
                face: face,
                nickname: nickname,
                postname: postname
            };

            var params = {
                cate: cate,
                inputName: reviewCurrentType,
                reviewType: reviewCurrentType,
                reviewLevel: reviewCurrentLevel
            };

            dom = renderUserbox(user, params);

            if (insertMode == 'insert') {
                $(dom).insertBefore(reviewCurrentEl.parent());
            } else {
                $(dom).replaceAll(reviewCurrentEl.parent());
            }

            layer.closeAll();
        });

        // 移除用户
        $(document).on('click', '.review-user-box[deletable] .review-user-avatar', function (ev) {
            $(this).parent().remove();
        });
    });
});

/**
 * 渲染用户选择弹层
 * @param data 渲染需要的数据
 * @param inputName input的name值
 * @param reviewLevel 审批级别(下标)
 * @returns {string}
 */
function renderUserSelector(data, inputName, reviewLevel) {
    var dom = '';
    dom += '<div class="layui-collapse">';
    for (var group in data) {
        dom += '<div class="layui-colla-item">';
        dom += '<div class="layui-colla-title">' + data[group].title + '</div>';
        dom += '<div class="layui-colla-content layui-show clearfix">';
        for (var index in data[group].users) {
            dom += renderUserbox(data[group].users[index], {
                inputName: inputName,
                reviewLevel: reviewLevel
            });
        }
        dom += '</div>';
        dom += '</div>';
    }
    dom += '</div>';

    return dom;
}

/**
 * 渲染单个用户
 * @param user 单个用户的数据
 * @param params 额外的参数，optional/deletable/add等
 * @returns {string|*}
 */
function renderUserbox(user, params) {
    params = {
        empty: params.empty ? params.empty : '',
        cate: params.cate ? params.cate : '',
        inputName: params.inputName ? params.inputName : 'reviewers',
        selector: params.selector ? params.selector : '',
        reviewType: params.reviewType ? params.reviewType : 'reviewers',
        reviewLevel: params.reviewLevel ? params.reviewLevel : ''
    };
    var float = params.float ? '' : 'float';

    var dom = '';
    dom += '<div class="review-user-box ' + params.empty + '" ' + params.cate + ' ' + float + '>';
    if (params.cate != 'add') {
        dom += '<input type="hidden" name="' + params.inputName + '[' + user.id + ']" value="' + user.id + '">';
    }
    dom += '<div class="review-user-avatar ' + params.selector + '" review-type="' + params.reviewType + '" review-level="' + params.reviewLevel + '">';
    dom += '<img src="' + user.face + '" alt="">';
    dom += '</div>';
    if (params.cate != 'add') {
        if (user.nickname) {
            dom += '<div class="review-user-name">' + user.nickname + '</div>';
        }
        if (user.postname) {
            dom += '<div class="review-user-footer" title="' + user.postname + '">' + user.postname + '</div>';
        }
    }
    dom += '</div>';

    return dom;
}

/**
 * 渲染显示在页面上的记录（历史审批人）
 * @param type 类型，是审批人还是抄送人
 * @param ruleActive 是否有规则
 * @param data 源数据
 * @param container 待插入的容器名称
 */
function renderUserList(type, ruleActive, data, container) {
    var allowAdd = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;


    var dom = '',
        user = {},
        params = {};
    var username = '',
        empty = '',
        avatar = '',
        id = '',
        postname = '';

    // 检查是否开启规则
    if (ruleActive) {
        if (type === 'reviewers') {
            // 有规则的审批人选择dom结构
            for (var level in data) {

                if (data[level].users.length == 1) {
                    username = data[level].users[0].nickname;
                    empty = '';
                    avatar = data[level].users[0].face;
                    id = data[level].users[0].id;
                } else {
                    username = '未选择';
                    empty = 'review-user-empty';
                    avatar = '/Public/home/img/face/init_avatar.png';
                    id = '';
                }
                postname = data[level].title;

                user = {
                    id: id,
                    face: avatar,
                    nickname: username,
                    postname: postname
                };

                params = {
                    selector: 'review-open-user-selector',
                    empty: empty,
                    cate: 'optional',
                    reviewType: type,
                    reviewLevel: level
                };

                dom += renderUserbox(user, params);
            }
        } else {
            user = {
                id: '',
                face: '/Public/home/img/face/add.png',
                nickname: '',
                postname: ''
            };

            params = {
                cate: 'add',
                reviewType: 'cc'
            };

            dom += renderUserbox(user, params);
        }
    } else {
        if (data.length) {
            // 如果存在历史审批人数据则遍历输出
            for (var level in data) {
                username = data[level].nickname;
                empty = '';
                avatar = data[level].face;

                user = {
                    id: data[level].id,
                    face: avatar,
                    nickname: username,
                    postname: data[level].title
                };

                params = {
                    reviewType: type,
                    inputName: type,
                    cate: 'deletable'
                };

                if (!allowAdd) delete params.cate;

                dom += renderUserbox(user, params);
            }
        }

        if (allowAdd) {
            user = {
                id: '',
                face: '/Public/home/img/face/add.png',
                nickname: '',
                postname: ''
            };

            params = {
                cate: 'add',
                reviewType: type,
                inputName: type
            };

            dom += renderUserbox(user, params);
        }
    }

    $(container).html(dom);
}
